﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Windows.Forms;
using System.IO;

using Smg.XML;
using Smg.DAL;
using Smg.Model;
using Smg.Source;

namespace Smg
{
    public partial class frmWiZard : Form
    {
        Hashtable ht = new Hashtable();
        string ConfigPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\StTools\\" + Application.ProductName;
        string connectionString = "";

        public frmWiZard()
        {
            InitializeComponent();
        }

        private void wizard1_Load(object sender, EventArgs e)
        {
            ht.Add("XML文件", "xml");
            ht.Add("HTML文件", "html");
            ht.Add("TXT文件", "txt");

            IDictionaryEnumerator ide = ht.GetEnumerator();
            while (ide.MoveNext())
            {
                this.cbbFileType.Items.Add(ide.Key);
            }
            this.InitSqlTemplateTable();
            this.dataGridView1.AllowUserToAddRows = false;

            this.cbbFileType.SelectedIndex = 1;
            this.cbbDBType.SelectedIndex = 0;
            this.txtProjectName.Focus();
            this.GetDBInfo();
        }

        private void wizard1_CloseFromCancel(object sender, CancelEventArgs e)
        {
            if (MessageBox.Show(this,
                "您确定要退出向导吗?",
                "退出向导", MessageBoxButtons.YesNo
                ) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void wizardPage1_CloseFromNext(object sender, Smg.WinForm.Wizard.PageEventArgs e)
        {
            if (this.txtProjectName.Text.Equals(""))
            {
                MessageBox.Show("请填写项目名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Page = this.wizardPage1;
            }
            else
            {
                string regURL = (@"^(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
                Regex rg = new Regex(regURL);

                if(!rg.IsMatch(this.txtURL.Text.Trim().ToLower()))
                {
                    MessageBox.Show("请填写正确的网址！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Page = this.wizardPage1;
                }
            }
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            string filepath = "";
            SaveFileDialog saveFD = new SaveFileDialog();

            string strFileType = ht[this.cbbFileType.Text].ToString();
            strFileType = this.cbbFileType.Text + "(*." + strFileType + ")|*." + strFileType;

            saveFD.Filter = strFileType;
            saveFD.FilterIndex = 1;
            saveFD.RestoreDirectory = true;
            saveFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFD.OverwritePrompt = true;
            if (saveFD.ShowDialog() == DialogResult.OK)
            {

                filepath = saveFD.FileName;
                this.txtFilePath.Text = filepath;
            }
        }

        private void rdbCFileType_Click(object sender, EventArgs e)
        {
            this.panelDBTyle.Visible = false;
            MessageBox.Show("按文件目录生成模式正在开发中\n请选择数据库生成模式！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void rdbCDBType_Click(object sender, EventArgs e)
        {
            this.panelDBTyle.Visible = true;
        }

        private void btnAccessBrowser_Click(object sender, EventArgs e)
        {
            string filepath = "";
            OpenFileDialog openFD = new OpenFileDialog();

            string strFileType = "Access文件(*.mdb)|*.mdb|All File(*.*)|*.*";

            openFD.Filter = strFileType;
            openFD.FilterIndex = 1;
            openFD.RestoreDirectory = true;
            openFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            if (openFD.ShowDialog() == DialogResult.OK)
            {

                filepath = openFD.FileName;
                this.txtAccessPath.Text = filepath;
            }
        }

        private void cbbDBType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbbDBType.SelectedIndex == 0)
            {
                this.panelAccess.Visible = true;
                this.panelSQL.Visible = false;
            }
            else if (this.cbbDBType.SelectedIndex == 1)
            {
                this.panelAccess.Visible = false;
                this.panelSQL.Visible = true;
            }
            else if (this.cbbDBType.SelectedIndex == 2)
            {
                this.panelAccess.Visible = false;
                this.panelSQL.Visible = false;
                MessageBox.Show("很抱歉，暂时还不支持MySql数据库\n稍后将推出此功能，尽情期待！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            this.btnTestConnection.Text = "测试中...";
            this.Cursor = Cursors.WaitCursor;
            GetConnectionString();

            try
            {
                MsSqlDBOpration msSqlDBOpration = new MsSqlDBOpration(this.connectionString);
                MessageBox.Show(msSqlDBOpration.TestConnection(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.btnTestConnection.Text = "测试连接(&T)";
                this.Cursor = Cursors.Default;
            }

        }

        private StProject CreateProject()
        {
            StProject project = new StProject();
            project.DateTimeValue = DateTime.Now;
            project.ProjectName = this.txtProjectName.Text.Trim();
            project.Url = this.txtURL.Text.Trim();
            project.FileType = ht[this.cbbFileType.Text].ToString();
            project.FilePath = this.txtFilePath.Text.Trim();
            project.GenerateMode = "DataBase";
            project.ConnectionString = this.CreateConnctionString();

            ArrayList arr = this.CreateSqlTemplates();

            for (int i = 0; i < arr.Count; i++)
            {
                project.SqlTemplates.Add((SqlTemplate)arr[i]);
            }

            return project;
        }


        private ArrayList CreateConnctionString()
        {
            ArrayList arrConnectringString = new ArrayList();

            DbConnectionString dbcs = new DbConnectionString();

            Secrecy se = new Secrecy();
            dbcs.ConnectionString = se.encode(this.connectionString);
            dbcs.Destination = (DbTypeDestination)Enum.Parse(typeof(DbTypeDestination), this.cbbDBType.Text, true);

            arrConnectringString.Add(dbcs);

            return arrConnectringString;
        }

        private ArrayList CreateSqlTemplates()
        {
            ArrayList arrSqlTemplates = new ArrayList();
            DataTable dt = Config.SqlTemplateTab;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                SqlTemplate st = new SqlTemplate();
                st.Sql = dt.Rows[i]["Sql"].ToString();
                st.UrlExpression = dt.Rows[i]["UrlExpression"].ToString();
                st.ChangeFreq = "weekly";
                st.Priority = dt.Rows[i]["Priority"].ToString();

                arrSqlTemplates.Add(st);
            }

            return arrSqlTemplates;
        }

        private void CheckAndCerateFolder(string Path)
        {
            if (!Directory.Exists(Path))
            {
                Directory.CreateDirectory(Path);
            }
        }

        private void wizardPage2_CloseFromNext(object sender, Smg.WinForm.Wizard.PageEventArgs e)
        {
            if (this.txtFilePath.Text.Equals(""))
            {
                MessageBox.Show("请选择文件保存路径！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Page = this.wizardPage2;
            }
            else
            {
                this.SaveDBInfo();
            }
        }

        private void wizardPage3_CloseFromNext(object sender, Smg.WinForm.Wizard.PageEventArgs e)
        {
            Panel panel = new Panel();
            if (this.cbbDBType.SelectedIndex == 0)
            {
                panel = this.panelAccess;
            }
            else if (this.cbbDBType.SelectedIndex == 1)
            {
                panel = this.panelSQL;
            }
            else
            {
                e.Page = this.wizardPage3;
            }

            foreach (Control c in panel.Controls)
            {
                if (c is TextBox)
                {
                    if (c.Text.Equals(""))
                    {
                        MessageBox.Show("请将信息填写完整！",Application.ProductName,MessageBoxButtons.OK,MessageBoxIcon.Information);
                        e.Page = this.wizardPage3;
                        break;
                    }
                }
            }

            GetConnectionString();
            this.SaveDBInfo();
        }

        private void btnAccessTest_Click(object sender, EventArgs e)
        {
            GetConnectionString();
            this.Cursor = Cursors.WaitCursor;

            try
            {
                OleDBOpration oleDBOpration = new OleDBOpration(this.connectionString);
                MessageBox.Show(oleDBOpration.TestConnection(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void GetConnectionString()
        {
            switch (this.cbbDBType.SelectedIndex)
            {
                case 0: connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.txtAccessPath.Text.Trim() + ";"; break;
                case 1: connectionString = "Data Source=" + this.txtServerName.Text.Trim() + ";uid=" + this.txtUserName.Text.Trim() + ";pwd=" + this.txtPassWord.Text.Trim() + ";DataBase=" + this.txtDataBase.Text.Trim() + ";"; break;
                case 2: connectionString = "MySql"; break;
                default: connectionString = ""; break;
            }

            Config.ConnectionString = this.connectionString;
        }

        private void wizardPage4_CloseFromNext(object sender, Smg.WinForm.Wizard.PageEventArgs e)
        {
            if (this.dataGridView1.Rows.Count <= 0)
            {
                MessageBox.Show("请设置模板！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Page = this.wizardPage4;
            }
        }

        private void wizardPageFinished_CloseFromNext(object sender, Smg.WinForm.Wizard.PageEventArgs e)
        {
            StProject stp = this.CreateProject();

            try
            {
                CheckAndCerateFolder(this.ConfigPath);
                this.ConfigPath += "\\" + this.txtProjectName.Text + ".stproj";
                Config.ProjectPath = this.ConfigPath;

                ObjectXMLSerializer<StProject>.Save(stp, Config.ProjectPath,XMLFormat.XML);
                MessageBox.Show("项目成功配置到'" + Config.ProjectPath + "'!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to save sitemap object!" + Environment.NewLine + Environment.NewLine + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            Form frm = new frmNewSqlTemplate();
            DataTable dt = Config.SqlTemplateTab;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                DataRow dr = dt.NewRow();
                dr[0] = Config.Sql;
                dr[1] = Config.UrlExpression;
                dr[2] = Config.ChangeFreq;
                dr[3] = Config.Priority;

                dt.Rows.Add(dr);
                //string[] strs = { Config.Sql, Config.UrlExpression, Config.Priority };
            }

            Config.SqlTemplateTab = dt;
            this.dataGridView1.DataSource = dt;
            this.dataGridView1.AutoResizeColumns();
            this.dataGridView1.Refresh();
        }

        //private void InitDataGridView()
        //{
        //    // Add columns to the DataGridView.
        //    dataGridView1.ColumnCount = 3;

        //    // Set the properties of the DataGridView columns.
        //    dataGridView1.Columns[0].Name = "Sql";
        //    dataGridView1.Columns[1].Name = "UrlExpression";
        //    dataGridView1.Columns[2].Name = "Priority";
        //    dataGridView1.Columns["Sql"].HeaderText = "Sql";
        //    dataGridView1.Columns["UrlExpression"].HeaderText = "UrlExpression";
        //    dataGridView1.Columns["Priority"].HeaderText = "Priority";

        //    dataGridView1.AllowUserToAddRows = false;
        //}

        private void InitSqlTemplateTable()
        {
            DataTable dt = new DataTable();
            DataColumn dcSql = new DataColumn("Sql");
            DataColumn dcUrlExpression = new DataColumn("UrlExpression");
            DataColumn dcPriority = new DataColumn("Priority");
            DataColumn dcChangeFreq = new DataColumn("ChangeFreq");

            dt.Columns.Add(dcSql);
            dt.Columns.Add(dcUrlExpression);
            dt.Columns.Add(dcChangeFreq);
            dt.Columns.Add(dcPriority);

            Config.SqlTemplateTab = dt;
        }

        private void SaveDBInfo()
        {
            Config.Url = this.txtURL.Text.Trim();
            Config.ConnectionString = this.connectionString;
            Config.DataBaseHost = this.txtServerName.Text.Trim();
            Config.DataBaseName = this.txtDataBase.Text.Trim();
            Config.DbPassWord = this.txtPassWord.Text.Trim();
            Config.DbUserName = this.txtUserName.Text.Trim();
            Config.AccessPath = this.txtAccessPath.Text.Trim();
            Config.DbType = this.cbbDBType.Text;
        }

        private void GetDBInfo()
        {
            this.connectionString = Config.ConnectionString;
            this.txtServerName.Text = Config.DataBaseHost;
            this.txtDataBase.Text = Config.DataBaseName;
            this.txtPassWord.Text = Config.DbPassWord;
            this.txtUserName.Text = Config.DbUserName;
            this.txtAccessPath.Text = Config.AccessPath;
            this.txtURL.Text = Config.Url;
            this.cbbDBType.SelectedText = Config.DbType;
        }
    }
}